package com.xianrenit.xianrenpuzi.manager.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.xianrenit.xianrenpuzi.common.handler.exception.SpzxException;
import com.xianrenit.xianrenpuzi.manager.listener.CateExcelDataListener;
import com.xianrenit.xianrenpuzi.manager.mapper.CategoryMapper;
import com.xianrenit.xianrenpuzi.manager.service.CategoryService;
import com.xianrenit.xianrenpuzi.model.dto.excel.CateExcelDto;
import com.xianrenit.xianrenpuzi.model.entity.product.Category;
import com.xianrenit.xianrenpuzi.model.result.ResultCodeEnum;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Resource
    CategoryMapper categoryMapper;
    @Resource
    CateExcelDataListener cateExcelDataListener;
    @Override
    public List<Category> listByPid(Long parentId) {
        List<Category> categories = categoryMapper.selectByPid(parentId);
        //使用每一个category的id查询他的下一级，如果有，hasChildren设置为true
        categories.forEach(category -> {
            Boolean hasChildren = categoryMapper.hasChildren(category.getId());
            category.setHasChildren(hasChildren);
        });
        return categories;
    }

    @Override
    public void importCates(MultipartFile excel) {
        try {
//        excel.getContentType():
            InputStream is = excel.getInputStream();
            if(is.available()==0){
                throw new SpzxException(ResultCodeEnum.FILE_UPLOAD_ERROR);
            }
            //1、为要读取的excel文件创建映射的实体类
            //2、创建回调监听器：处理读取到的数据(保存数据到数据库)
            //3、从MultipartFile中获取数据流开始解析
            EasyExcel.read(is)
                    .head(CateExcelDto.class)
                    .registerReadListener(cateExcelDataListener)
                    .sheet(0)
                    .doRead();
        } catch (Exception e) {
            throw new SpzxException(ResultCodeEnum.FILE_UPLOAD_ERROR,e);
        }

    }

    @Override
    public void exportCates(HttpServletResponse response) {
        try {
            //1、查询要写入到excel的数据集合
            List<CateExcelDto> cateExcelDtos = categoryMapper.selectAll();
            //2、配置响应报文头： 告诉浏览器如何解析响应体内容(让浏览器将响应体的内容当成一个附件下载，并指定文件名称)
            String fileName = "商品分类_"
                    +new DateTime().toString("yyyy-MM-dd") +".xlsx";
            // %2B8
            fileName = URLEncoder.encode(fileName,"UTF-8");
            System.out.println(fileName);
            response.setHeader("content-disposition" , "attachment;filename="+fileName);
            //3、使用Easyexcel写数据到excel文件中: 写到响应体中
            EasyExcel.write(response.getOutputStream()) //将数据写入到响应对象的输出流中
                    .excelType(ExcelTypeEnum.XLSX) //指定写出的excel文件的格式
                    .head(CateExcelDto.class) //excel文件的表头
                    .sheet("分类数据")  //工作簿名称
                    .doWrite(cateExcelDtos);  //写数据
        } catch (Exception e) {
            throw new SpzxException(ResultCodeEnum.FILE_EXPORT_ERROR,e);
        }

    }

//    public static void main(String[] args) throws UnsupportedEncodingException {
//        String decode = URLDecoder.decode("%E5%95%86%E5%93%81%E5%88%86%E7%B1%BB", "UTF-8");
//        System.out.println(decode);
//    }
}
